package com.springboot.mall.common;

import com.springboot.mall.exception.MallExceptionEnum;

/*
 *
 *通用返回对象
 *@data 2022-05-08
 */
public class ApiRestResponse<T> {

    //更具接口文档中返回的数据来实现这个类
    /*
    * {    "status": 10000,    "msg": "SUCCESS",    "data": null}
    * data是一个泛型，不固定对象类型，所以用T表示
    * */

    private Integer status;

    private String msg;

    private T data;

    //private static final作用
    private static final int OK_CODE = 10000;
    private static final String OK_MSG = "SUCCESS";

    //构造方法

    public ApiRestResponse(Integer status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ApiRestResponse(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public ApiRestResponse() {
        this(OK_CODE,OK_MSG);
    }

    public static <T> ApiRestResponse<T> success(){
        //调用 ApiRestResponse() 无参方法，选择默认值
        return new ApiRestResponse<>();
    }

    public static <T> ApiRestResponse<T> success(T result){
        ApiRestResponse<T> response = new ApiRestResponse<>();
        response.setData(result);
        return response;
    }

    public static <T> ApiRestResponse<T> error(Integer code,String msg){
        return new ApiRestResponse<>(code,msg);
        //错误信息不想每次都自己写，可以通过枚举，然后直接找到用。既然是错误，那就和异常相关了
    }

    public static <T> ApiRestResponse<T> error(MallExceptionEnum ex){
        return new ApiRestResponse<>(ex.getCode(),ex.getMsg());
        //
    }

    @Override
    public String toString() {
        return "ApiRestResponse{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static int getOkCode() {
        return OK_CODE;
    }

    public static String getOkMsg() {
        return OK_MSG;
    }
}
